package com.smbms.commons.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smbms.commons.bean.Users;
import com.smbms.commons.config.JsonResult;
import com.smbms.commons.config.JwtConfig;
import com.smbms.commons.config.ResultCode;
import com.smbms.commons.config.ResultTool;
import com.smbms.commons.mapper.UsersMapper;
import com.smbms.commons.service.UsersService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public JsonResult<String> login(Users user) {
        user = usersMapper.login(user);
        if(user==null){
            return ResultTool.fail(ResultCode.USER_CREDENTIALS_ERROR);
        }
        int gender = user.getGender();
        if(gender==1){
            user.setUserSex("女");
        }else{
            user.setUserSex("男");
        }
        user.setUserPassword(null);
        //生成jwt字符串
        String jwt = JwtConfig.getJwtToken(user);
        //将jwt存入到redis中
        //设置使用String编码集
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setValueSerializer(stringSerializer);
        ValueOperations<String, String> value = redisTemplate.opsForValue();
        value.set("token:"+user.getId(),jwt,JwtConfig.EXPIRE);
        return ResultTool.success(jwt);
    }

    @Cacheable(cacheNames = "findAllUsers",key = "#page")
    @Override
    public JsonResult<PageInfo<Users>> findAllUsers(Integer page) {
        PageHelper.startPage(page,2);
        List<Users> list = usersMapper.findAllUsers();
        PageInfo<Users> pageInfo=new PageInfo<>(list);
        return ResultTool.success(pageInfo);
    }

    @Cacheable(cacheNames = "findUserByNameAndRoleName",key = "#name+'.'+#role+'.'+#page")
    @Override
    public JsonResult<PageInfo<Users>> findUserByNameAndRoleName(String name, Integer role, Integer page) {
        PageHelper.startPage(page,2);
        List<Users> list = usersMapper.findUserByNameAndRoleName(name,role);
        PageInfo<Users> pageInfo=new PageInfo<>(list);
        return ResultTool.success(pageInfo);
    }
}
